package com.moli.runner;

import com.moli.domain.entity.Article;
import com.moli.mapper.ArticleMapper;
import com.moli.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author： XC
 * @Date： 2023-06-08 10:49
 * @Description： 在应用启动时把博客的浏览量存储到redis中
 */

@Component
public class ViewCountRunner implements CommandLineRunner {

	@Resource
	private ArticleMapper articleMapper;

	@Autowired
	private RedisCache redisCache;

	@Override
	public void run(String... args) throws Exception {
		//查询博客信息  key:id、value:viewCount
		List<Article> articles = articleMapper.selectList(null);  //无需传入条件就可以查询博客的所有信息
		//stream流的方式 查询id viewCount
		Map<String, Integer> viewCountMap = articles.stream()
				.collect(Collectors.toMap(article -> article.getId().toString(), article -> {
					return article.getViewCount().intValue();//
				}));
		//存储到redis中
		redisCache.setCacheMap("article:viewCount",viewCountMap);
	}
}
